//
//  DDMyAnswerContentVC.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/7/18.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDMyAnswerContentVC.h"
#import "MJRefresh.h"
#import "DDTopic.h"
#import "DDNetWorkAPIClient.h"
#import "UIImageView+WebCache.h"
#import "DDMyAnswerFootToolButtonView.h"
#import "DDMyAnswerEncriptFTButoonView.h"
#import "DDMyAnswerEncriptAndOpenFTButoonView.h"
#import "DDZdtjVC.h"
#import "TNColorScrollViewController.h"
#import "DDQuestionView.h"
#import "DDTagDB.h"
#import "DDTagVC.h"
#import "DDCkdaVC.h"
#import "DDCkfzVC.h"
#import "DDCkdaQuestion.h"
#import "DDShareViewController.h"

#import "DDQuestionChooseCourseViewController.h"

@interface DDMyAnswerContentVC ()<DDQuestionChooseCourseViewControllerDelegate>


@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *datas;

@property (nonatomic,assign)int pageIndex;
@property (nonatomic,assign)int pageSize;

@property (nonatomic,strong)DDZdtjVC *zdtj;


@property (nonatomic,strong)TNColorScrollViewController *colorScrollVC;
@property (nonatomic,strong)NSArray *questions;
@property (nonatomic,strong)DDTopicDataCellModel *model;


@property (nonatomic,strong)DDTopicDataCellModel *selectTopic;
@property (nonatomic, strong)NSMutableArray *allArray;



@end

@implementation DDMyAnswerContentVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    [self createData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createUI
{
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.01f)];
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(reloadPostData)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"别再拉了,裤子要被拉下来了...";
    
    self.tableView.footerPullToRefreshText = @"上提可以刷新了";
    self.tableView.footerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.footerRefreshingText = @"别再拉了,裤子要被拉下来了...";
    

}


- (void)createData
{
    _datas = [NSMutableArray array];
    _pageSize = 10;
    _pageIndex = 0;
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(popTagView:) name:@"popTagView" object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(clearPopTagView) name:@"clearTagView" object:nil];
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(didselectSearchText:) name:@"didChangeText" object:nil];
}

-(void)clearPopTagView
{
    [[self.colorScrollVC.view viewWithTag:10001] removeFromSuperview];
}
- (void)popTagView:(NSNotification *)note
{
    UIView *view = [self.colorScrollVC.view viewWithTag:10001];
    if (view) {
        [self clearPopTagView];
        return;
    }
    
    DDTagVC * _tagVC = [[DDTagVC alloc] initWithNibName:@"DDTagVC" bundle:nil];
    [self.colorScrollVC addChildViewController:_tagVC];
    NSDictionary *dict = note.object;
    _tagVC.x = [dict objectForKey:@"x"];
    _tagVC.y = [dict objectForKey:@"y"];
    _tagVC.index = [dict objectForKey:@"index"];
    _tagVC.qid = [dict objectForKey:@"qid"];
    _tagVC.page = [dict objectForKey:@"page"];
    CGRect rect = _tagVC.view.frame;
    _tagVC.view.frame = CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height-150, 10, 0);
    _tagVC.view.tag = 10001;
    [self.colorScrollVC.view addSubview:_tagVC.view];
    _tagVC.view.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _tagVC.view.frame = CGRectMake(0, self.colorScrollVC.view.frame.size.height/2, rect.size.width, rect.size.height);
    }];
    
    int selectPage = (int)_tagVC.page.integerValue - 1;
    __weak DDMyAnswerContentVC *weakSelf = self;
    _tagVC.result = ^(NSString *result,id object,NSString *type)
    {
        NSArray *views = weakSelf.colorScrollVC.view.scrollView.subviews;
        if (views.count > 0) {
            DDQuestionView *qview = views[selectPage];
            [qview.tableView reloadData];
        }
    };
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
#pragma mark - 私有方法
-(void)reloadPostData
{
    _pageIndex = 0;
    NSDictionary *params = @{@"type":[self selectTab],@"pageIndex":[NSString stringWithFormat:@"%d",_pageIndex],@"pageSize":[NSString stringWithFormat:@"%d",_pageSize]};
    DDNetWorkAPIClient *netwrok = [[DDNetWorkAPIClient alloc]init];
    [netwrok mainAnswerList:params completionBlock:^(BOOL isSuccess, NSString *message, NSString *status,id object) {
        DDTopic *topic = (DDTopic *)object;
        NSLog(@"=============%@==============", topic);
        _datas = [NSMutableArray arrayWithArray:topic.list];
        _allArray = _datas;
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        [self.tableView footerEndRefreshing];
    }];
    
}
-(void)footerRereshing
{
    _pageIndex++;
    
    NSDictionary *params = @{@"type":[self selectTab],@"pageIndex":[NSString stringWithFormat:@"%d",_pageIndex],@"pageSize":[NSString stringWithFormat:@"%d",_pageSize]};
    DDNetWorkAPIClient *netwrok = [[DDNetWorkAPIClient alloc]init];
    [netwrok mainAnswerList:params completionBlock:^(BOOL isSuccess, NSString *message, NSString *status,id object) {
        DDTopic *topic = (DDTopic *)object;
        [_datas addObjectsFromArray:topic.list];
        _allArray = _datas;
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        [self.tableView footerEndRefreshing];
    }];
}

#pragma mark -UITableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _datas.count;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 90;
    DDTopicDataCellModel *topicModel = [_datas objectAtIndex:indexPath.section];
    NSArray *questions = topicModel.questions;
    NSArray *bodys = questions.count > 0 ?((DDTopicQuestion *)questions[0]).body : nil;
    bool isimage = NO;
    bool istext = NO;
    for(int i = 0; i < bodys.count;i++)
    {
        DDTopicQuestionBody *body = bodys[i];
        NSString *type = body.type;
        if ([type isEqualToString:@"IMAGE"])
        {
            if (isimage) {
                continue;
            }
            height = height + 130;
            isimage = YES;
            break;
        }
        else if([type isEqualToString:@"TEXT"])
        {
            CGSize size = [self autoLabelString1:tableView string:body.text];
            
            if (istext) {
                continue;
            }
            
            height = height + size.height;
         
            istext = YES;
        }
    }
    CGSize size = [self autoLabelString:tableView string:topicModel.title];
    height = height + size.height;
    if (_typeIndex == 0) {//加个加密框
        height += 55;
    }
    return height;
}
- (CGSize)autoLabelString1:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
    //设置一个行高上限
    CGSize size = CGSizeMake(view.frame.size.width - 10,60);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    return labelsize;
}

- (CGSize)autoLabelString:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
    //设置一个行高上限
    CGSize size = CGSizeMake(view.frame.size.width - 10,2000);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    return labelsize;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 50;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    __weak typeof(self) weakSelf = self;
    if (_typeIndex == 0) {
        DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
        if ([topicModel.showAnswer isEqualToString:@"1"]) {
            
            static NSString *footIdentifier = @"DDMyAnswerEncriptAndOpenFTButoonView";
            
            DDMyAnswerEncriptAndOpenFTButoonView *footView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:footIdentifier];
            footView.section = section;
            
            if(!footView) {
                footView = [[[NSBundle mainBundle] loadNibNamed:@"DDMyAnswerEncriptAndOpenFTButoonView"
                                                          owner:self
                                                        options:nil] objectAtIndex:0];
            }
            
            footView.SubmitRefershHDButtonBlock = ^(UIButton *sender,NSInteger s)
            {
                DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
                [self question:topicModel.password];
                
            };
            footView.SubmitCkdaButtonBlock = ^(UIButton *sender,NSInteger s)
            {
                DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
                // DDCkdaVC *ckdaVC = [[DDCkdaVC alloc] initWithNibName:@"DDCkdaVC" bundle:nil];
                //[self.navigationController pushViewController:ckdaVC animated:YES];
                //ckdaVC.topic = topicModel;
                [self ckdaQuestion:topicModel showAnswer:YES];
                
                //[[NSNotificationCenter defaultCenter] postNotificationName:@"switchVC" object:ckdaVC];
            };
            footView.SubmitZdtjButtonBlock = ^(UIButton *sender,NSInteger s)
            {
                DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
                weakSelf.zdtj = [[DDZdtjVC alloc] initWithNibName:@"DDZdtjVC" bundle:nil];
                weakSelf.zdtj.topicId = topicModel.id;
                weakSelf.zdtj.showAnswer = YES;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:weakSelf.zdtj];
            };
            footView.SubmitCkfzButtonBlock = ^(UIButton *sender,NSInteger s)
            {
                DDCkfzVC *ckfz = [[DDCkfzVC alloc]initWithNibName:@"DDCkfzVC" bundle:nil];
                ckfz.topic = topicModel;
                if (topicModel.questions) {
                    ckfz.question = topicModel.questions[0];
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:ckfz];
            };
            
            footView.contentView.backgroundColor = [UIColor whiteColor];
            
            return footView;
            
            
        }else{
            static NSString *footIdentifier = @"DDMyAnswerEncriptFTButoonView";
            
            DDMyAnswerEncriptFTButoonView *footView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:footIdentifier];
            footView.section = section;
            
            if(!footView) {
                footView = [[[NSBundle mainBundle] loadNibNamed:@"DDMyAnswerEncriptFTButoonView"
                                                          owner:self
                                                        options:nil] objectAtIndex:0];
            }
            
            footView.SubmitRefershHDButtonBlock = ^(UIButton *sender,NSInteger s)
            {
                DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
                [self question:topicModel.password];
                
            };
            footView.SubmitCkdaButtonBlock = ^(UIButton *sender,NSInteger s)
            {
                DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
                // DDCkdaVC *ckdaVC = [[DDCkdaVC alloc] initWithNibName:@"DDCkdaVC" bundle:nil];
                //[self.navigationController pushViewController:ckdaVC animated:YES];
                //ckdaVC.topic = topicModel;
                [self ckdaQuestion:topicModel showAnswer:NO];
                //[[NSNotificationCenter defaultCenter] postNotificationName:@"switchVC" object:ckdaVC];
            };
            footView.SubmitZdtjButtonBlock = ^(UIButton *sender,NSInteger s)
            {
                DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
                weakSelf.zdtj = [[DDZdtjVC alloc] initWithNibName:@"DDZdtjVC" bundle:nil];
                weakSelf.zdtj.topicId = topicModel.id;
                weakSelf.zdtj.showAnswer = NO;
                //UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:weakSelf.zdtj];
                
                //[weakSelf presentViewController:nav animated:YES completion:nil];
                //[weakSelf.navigationController pushViewController:weakSelf.zdtj animated:YES];
                //[[NSNotificationCenter defaultCenter] postNotificationName:@"switchVC" object:weakSelf.zdtj];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:weakSelf.zdtj];
            };
            footView.contentView.backgroundColor = [UIColor whiteColor];
            
            return footView;
        }
        
       
    }else{
        static NSString *footIdentifier = @"DDMyAnswerFootToolButtonView";
        
        DDMyAnswerFootToolButtonView *footView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:footIdentifier];
        if(!footView) {
            footView = [[[NSBundle mainBundle] loadNibNamed:@"DDMyAnswerFootToolButtonView"
                                                      owner:self
                                                    options:nil] objectAtIndex:0];
        }
        footView.SubmitShareButtonBlock = ^(UIButton *button, NSInteger  section){
            [DDShareViewController showShareWithController:self];
        };
        footView.contentView.backgroundColor = [UIColor whiteColor];
        return footView;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    DDTopicDataCellModel *topicModel = [_datas objectAtIndex:indexPath.section];
    NSArray *questions = topicModel.questions;
    float start_X = 5;
    float start_Y = 5;
    
    
    UIImageView *header_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(start_X, start_Y, 50, 50)];
    //header_imageView.image = [UIImage imageNamed:@"user_header"];
    [header_imageView sd_setImageWithURL:[NSURL URLWithString:topicModel.userAvatarUrl] placeholderImage:[UIImage imageNamed:@"首页列表头像-通用"]options:SDWebImageRefreshCached];
    header_imageView.layer.cornerRadius = 25.0;
    header_imageView.layer.masksToBounds = YES;
    [cell.contentView addSubview:header_imageView];
    
    UILabel *name_label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:header_imageView sp:10],header_imageView.frame.origin.y+5 , 200, 24)];
    name_label.text = topicModel.userName;
    name_label.textColor = RGB(124,203,203);
    [cell.contentView addSubview:name_label];
    
    UILabel *time_label = [[UILabel alloc] initWithFrame:CGRectMake(name_label.frame.origin.x,[self yPostiong:name_label sp:5] , 200, 16)];
    time_label.text = [self convertTime:topicModel.createTime];//@"1天前";
    time_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
    time_label.textColor = [UIColor lightGrayColor];
    [cell.contentView addSubview:time_label];
   
    
    
    
    
    UIButton *typeButton = [UIButton buttonWithType:UIButtonTypeCustom];
     typeButton.frame = CGRectMake(tableView.frame.size.width - 50, name_label.frame.origin.y+5, 100, 18);
    
    NSString *typeName = topicModel.courseName;//questions.count > 0 ?((DDTopicQuestion *)questions[0]).typeName : @"";
    //题目组
    typeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    //但是问题又出来，此时文字会紧贴到做边框，我们可以设置
    typeButton.contentEdgeInsets = UIEdgeInsetsMake(0,20, 0, 0);
    if (questions.count > 1) {
        [typeButton setBackgroundImage:[UIImage imageNamed:@"题目组背景"] forState:UIControlStateNormal];
        typeName = typeName ? [NSString stringWithFormat:@"%@/",typeName]:@"";
        [typeButton setTitle:[NSString stringWithFormat:@"%@%lu",typeName,(unsigned long)questions.count] forState:UIControlStateNormal];
    }else{
        [typeButton setBackgroundImage:[UIImage imageNamed:@"icon_tag"] forState:UIControlStateNormal];
        [typeButton setTitle:typeName forState:UIControlStateNormal];
    }
    
    if (typeName.length > 0) {
        typeButton.frame = CGRectMake(tableView.frame.size.width - [self autoSize:typeButton string:typeName].width-20, name_label.frame.origin.y+5, [self autoSize:typeButton string:typeName].width+20, 18);
    }
    
    typeButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:10.0];
    [typeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    ///[typeButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    //[typeButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    typeButton.tag = 1100+indexPath.section;
    [typeButton addTarget:self action:@selector(typeChangeCourseName:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:typeButton];
    
    
   
    
    UILabel *gold_label = [[UILabel alloc] initWithFrame:CGRectMake(typeButton.frame.origin.x-(typeButton.frame.size.width/2),  name_label.frame.origin.y+3, 15, 16)];
    gold_label.text = topicModel.reward;
    gold_label.textAlignment = NSTextAlignmentLeft;
    gold_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
    gold_label.textColor = [UIColor orangeColor];
    [cell.contentView addSubview:gold_label];
    
    
    UIImageView *gold_imageview = [[UIImageView alloc] initWithFrame:CGRectMake([self xxPostiong:gold_label sp:5], name_label.frame.origin.y+5, 12, 12)];
    gold_imageview.image = [UIImage imageNamed:@"icon_gold"];
    [cell.contentView addSubview:gold_imageview];
    
    if (_typeIndex == 0 || _typeIndex == 2) {
        gold_imageview.hidden = YES;
        gold_label.hidden = YES;
    }
    
    UILabel *content_label = [[UILabel alloc] initWithFrame:CGRectMake(header_imageView.frame.origin.x,[self yPostiong:header_imageView sp:10] , tableView.frame.size.width -10, 18)];
    content_label.numberOfLines = 3;
    
    NSString *title = @"";
    if (questions.count > 0) {
        DDTopicQuestion *question = questions[0];
        NSArray *bodys = question.body;
        if (bodys.count > 0) {
            DDTopicQuestionBody * body = bodys[0];
            title = body.text;
        }else{
            title = @"";
        }
        
    }

    if (![topicModel.type isEqualToString:@"1"]) {
        content_label.text = title; //topicModel.title;
    }else{
        content_label.text = topicModel.title?topicModel.title:title;
    }

    CGSize size = [self autoLabelString1:tableView string:content_label.text];
    content_label.frame = CGRectMake(header_imageView.frame.origin.x,[self yPostiong:header_imageView sp:10] , tableView.frame.size.width -10, size.height);
    content_label.font = [UIFont fontWithName:@"Arial" size:17.0];
    [cell.contentView addSubview:content_label];
    
   

    
   // bool isimage = NO;
   // bool istext = NO;
    NSArray *bodys = questions.count > 0 ?((DDTopicQuestion *)questions[0]).body : nil;
    int autoHeigth = [self yPostiong:content_label sp:20] ;
    for(int i = 0; i < bodys.count;i++)
    {
        DDTopicQuestionBody *body = bodys[i];
        NSString *type = body.type;
//        if ([type isEqualToString:@"TEXT"]) {
//            
//            UILabel *content_label = [[UILabel alloc] initWithFrame:CGRectMake(header_imageView.frame.origin.x,[self yPostiong:header_imageView sp:10] , tableView.frame.size.width -10, 18)];
//            content_label.numberOfLines = 0;
//            
//            content_label.text = body.text;
//            CGSize size = [self autoLabelString:tableView string:body.text];
//            content_label.frame = CGRectMake(header_imageView.frame.origin.x,[self yPostiong:header_imageView sp:10+autoHeigth] , tableView.frame.size.width -10, size.height);
//            autoHeigth += size.height + 10;
//            
//            [cell.contentView addSubview:content_label];
//        }
//        else if ([type isEqualToString:@"IMAGE"])
        if ([type isEqualToString:@"IMAGE"])
        {
            UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(header_imageView.frame.origin.x,autoHeigth, tableView.frame.size.width -10, 130.0)];
            autoHeigth += 130 + 5;
            
            [imageView sd_setImageWithURL:[NSURL URLWithString:body.url] placeholderImage:[UIImage imageNamed:@"home_pic_04.png"]options:SDWebImageRefreshCached];
            //imageView.image = [self OriginImage:imageView.image scaleToSize:imageView.frame.size];
            //                imageView.clipsToBounds  = YES;
            //                imageView.contentMode = UIViewContentModeCenter|UIViewContentModeLeft;
            imageView.contentMode =  UIViewContentModeScaleAspectFill;
            //imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
            imageView.clipsToBounds  = YES;
            [cell.contentView addSubview:imageView];
            //content_label.frame = CGRectMake(header_imageView.frame.origin.x, [self yPostiong:imageView sp:0],tableView.frame.size.width -10, 44);
            break;
        }
    }

//    UILabel *number_people_label = [[UILabel alloc] initWithFrame:CGRectMake(tableView.frame.size.width-60,[self yPostiong:name_label sp:3] , 200, 24)];
//    number_people_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
//    number_people_label.textColor = RGB(128, 128, 128);
//    number_people_label.text = [NSString stringWithFormat:@"%@人回答",topicModel.answerNumber];
//    [cell.contentView addSubview:number_people_label];
    
    if (_typeIndex == 0) {//密码框
            UILabel *pwd_label = [[UILabel alloc] initWithFrame:CGRectMake((tableView.frame.size.width/2-100),autoHeigth, 200, 44)];
            pwd_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
            pwd_label.textColor = RGB(128, 128, 128);
            pwd_label.textAlignment = NSTextAlignmentCenter;
            pwd_label.layer.cornerRadius = 10.0;
            pwd_label.layer.borderColor = RGB(27, 142, 227).CGColor;
            pwd_label.layer.borderWidth = 1.0;
            pwd_label.layer.masksToBounds = YES;
            pwd_label.text = [NSString stringWithFormat:@"密码: %@", topicModel.password];
            [cell.contentView addSubview:pwd_label];
    }
    
    return cell;

}

-(void)typeChangeCourseName:(UIButton *)sender
{
    
    NSInteger section = sender.tag - 1100;
    _selectTopic = [_datas objectAtIndex:section];
    int type = 0;
    //0-大家帮 1-加密题 2-悬赏题
    if (_typeIndex == 1) {
        type = 2;
    }else if (_typeIndex == 0){
        type = 1;
    }else if (_typeIndex == 2)
    {
        type = 0;
    }
    
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"是否修改科目归类" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
    alert.tag = type;

    
    //[self.navigationController pushViewController:vc animated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        DDQuestionChooseCourseViewController * vc = [[DDQuestionChooseCourseViewController alloc]init];
        vc.delegate = self;
        vc.info_publishType = alertView.tag;
        [self presentViewController:vc animated:YES completion:nil];
    }
}

-(void)choosedCourse:(ModelQuestionCourseElement *)element{
    NSDictionary * tempDic = @{
                               @"topicId" : _selectTopic.id,
                               @"courseId" : element.info_id,
                               };
    __weak DDMyAnswerContentVC *weakSelf = self;
    DDNetWorkAPIClient *netwrok = [[DDNetWorkAPIClient alloc]init];
    [netwrok mainTopicTagAdd:tempDic completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        //        [self.myCollectionView headerBeginRefreshing];
        //[self getData];
        [weakSelf.tableView reloadData];
        
        [weakSelf.tableView headerBeginRefreshing];
    }];
}

-(float) xxPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.origin.x - view.frame.size.width -  sp;
}

-(float) yyPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.origin.y - view.frame.size.height- sp;
}


- (CGSize)autoSize:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
    //设置一个行高上限
    CGSize size = CGSizeMake(1000,44);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    return labelsize;
}

#pragma mark - 公用
-(UIImage *)OriginImage:(UIImage *)image scaleToSize:(CGSize)size{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
//- (NSIndexPath *)tableView:tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return nil;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //if (_typeIndex == 1) {
    
    
    
        DDTopicDataCellModel *topicModel = [_datas objectAtIndex:indexPath.section];
    if ([topicModel.showAnswer isEqualToString:@"1"]) {
        [self ckdaQuestion:topicModel showAnswer:YES];
    }else{
        [self ckdaQuestion:topicModel showAnswer:NO];
    }
    
    //}
}

-(float) xPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.width+view.frame.origin.x + sp;
}

-(float) yPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.height+view.frame.origin.y + sp;
}

- (NSString *)convertTime:(NSString *)time
{
    if (!time || [@"" isEqualToString:time]) {
        return @"";
    }
    
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    long a =  [timeSp longLongValue] - time.longLongValue/1000;
    
    long day = a/(3600*24);
    
    if (day < 360 && day > 30) {
        return [NSString stringWithFormat:@"%ld个月前",day/30];
    }
    else if (day >360){
        return [NSString stringWithFormat:@"%ld年以前",day/360];
    }
    else if (day == 0)
    {
        long second = a/3600;
        if (second > 0 && second < 24) {
            return [NSString stringWithFormat:@"%ld小时前",second];
        }else{
            return [NSString stringWithFormat:@"%ld分钟前",a/60];
        }
        
    }
    else if (day > 1 && day < 6){
        return [NSString stringWithFormat:@"%ld天前",day];
    }else{
        //实例化一个NSDateFormatter对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设定时间格式,这里可以设置成自己需要的格式
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        //用[NSDate date]可以获取系统当前时间
        NSDate *d = [NSDate dateWithTimeIntervalSince1970:time.longLongValue/1000];
        NSString *dateStr = [dateFormatter stringFromDate:d];
        return dateStr;
    }
    return @"";
}

-(NSString *)selectTab
{
    NSString *type = @"0";
    if (_typeIndex == 0) {
        type = @"1";
    }else if (_typeIndex == 1)
    {
        type = @"2";
    }else if (_typeIndex == 2)
    {
        type = @"0";
    }
    return type;
}

-(void)question:(NSString *)pass
{
    NSDictionary *params = @{@"type":@"1",@"password":pass};
    DDNetWorkAPIClient *netwrok = [[DDNetWorkAPIClient alloc]init];
    [MBProgressHUD showMessag:@"正在加载..." toView:self.view];
    
    
    [netwrok mainTopicList:params completionBlock:^(BOOL isSuccess, NSString *message, NSString *status,id object) {
        if (object) {
            DDTopic *topic = object;
            _model = topic.list[0];
            _questions = _model.questions;
            NSMutableArray *qustionViews = [NSMutableArray array];
            for (int i = 0; i < _questions.count; i++)
            {
                DDTopicQuestion *question = _questions[i];
                TNColorViewData *viewData = [[TNColorViewData alloc] initWithCustomClass:[DDQuestionView class]];
                viewData.question = question;
                viewData.page = i+1;
                
                BOOL show = NO;
                if (_model.showAnswer&&[_model.showAnswer isEqualToString:@"1"]) {
                    show = YES;
                }
                viewData.showAnswer = show;

                viewData.total = _questions.count;
                [qustionViews addObject:viewData];
                
            }
            TNColorScrollViewConfig *config = [[TNColorScrollViewConfig alloc] initWithColorDataObjects:qustionViews bounces:YES showsHorizontalScrollIndicator:NO showsVerticalScrollIndicator:NO pagingEnabled:YES scrollHorizontal:YES];
            
//            self.colorScrollVC = [[TNColorScrollViewController alloc] initWithColorScrollViewConfig:config displayMedia:YES cssStyle:DDCSSStyleAnswer];
//            self.colorScrollVC.topicID = _model.id;
//            self.colorScrollVC.showAnswer = _model.showAnswer;
//            //self.colorScrollVC.isDisplayMedia = NO;
//            self.colorScrollVC.currentScrollerPage = ^(NSInteger currentPage){
//                NSLog(@"%ld",(long)currentPage);
//            };
            self.colorScrollVC = [[TNColorScrollViewController alloc] initWithColorScrollViewConfig:config displayMedia:YES cssStyle:DDCSSStyleAnswer];
            self.colorScrollVC.topicID = _model.id;
            self.colorScrollVC.topicType = @"1";
            self.colorScrollVC.topic = _model;
            self.colorScrollVC.showAnswer = _model.showAnswer;
            //self.colorScrollVC.isDisplayMedia = YES;
            self.colorScrollVC.currentScrollerPage = ^(NSInteger currentPage){
                NSLog(@"%ld",(long)currentPage);
            };
            __weak DDMyAnswerContentVC *weakSelf = self;
            self.colorScrollVC.preScrollerPage = ^(NSInteger prePage){
                // NSLog(@"%d",prePage);
                DDNetWorkAPIClient *netwrok = [[DDNetWorkAPIClient alloc]init];
                DDTopicQuestion *question = weakSelf.questions[prePage];
                //NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                //NSString *result = [userDefault objectForKey:@"result"];
                DDQuestionView *questionView =  weakSelf.colorScrollVC.view.scrollView.subviews[prePage];
                NSString *result = questionView.result;
                
                //答案集合上传
                NSString *explanationJson = @"";
                NSArray *answers = questionView.answers;
                NSMutableArray *explanations = [NSMutableArray array];
                for (int i = 0; i < answers.count ; i++) {
                    NSString *ext = [answers[i] pathExtension];
                    if ([ext isEqualToString:@"jpg"]) {
                        //保存泡泡标签
                        NSArray *tags =   [DDTagDB searchWithWhere:[NSString stringWithFormat:@"qid='%@' AND tagIndex='%d'",question.id,i] orderBy:nil offset:0 count:0];
                        NSMutableArray *tagLabels = [NSMutableArray array];
                        
                        for (DDTagDB *tagdb in tags) {
                            if ([tagdb.type isEqualToString:@"IMAGE"]||[tagdb.type isEqualToString:@"AUDIO"]) {
                                NSDictionary *dict = @{@"type":[tagdb.type isEqualToString:@"AUDIO"]?@"VOICE":tagdb.type,@"x":tagdb.x,@"y":tagdb.y,@"url":tagdb.result};
                                [tagLabels addObject:dict];
                            }else if ([tagdb.type isEqualToString:@"TEXT"]){
                                NSDictionary *dict = @{@"type":tagdb.type,@"x":tagdb.x,@"y":tagdb.y,@"text":tagdb.result};
                                [tagLabels addObject:dict];
                            }
                        }
                        NSDictionary *pngDict = @{@"type":@"IMAGE",@"url":answers[i],@"labels":tagLabels};
                        [explanations addObject:pngDict];
                    }
                    if ([ext isEqualToString:@"caf"]) {
                        NSDictionary *cafDict = @{@"type":@"VOICE",@"url":answers[i]};
                        [explanations addObject:cafDict];
                    }
                    NSError *error;
                    NSData * JSONData = [NSJSONSerialization dataWithJSONObject:explanations
                                                                        options:kNilOptions
                                                                          error:&error];
                    explanationJson = [[NSString alloc]initWithData:JSONData encoding:NSUTF8StringEncoding];
                }
                
                
                [netwrok mainAnswerSave:@{@"topicId":weakSelf.model.id,@"qid":question.id,@"answer":result==nil?@"":result,@"costSeconds":@"10",@"explanations":explanationJson} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
                    NSLog(@"%@",object);
                    if (object) {
                        
                    }
                    [MBProgressHUD showMessag:message toView:weakSelf.view];
                    
                }];
            };
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:self.colorScrollVC];
        }else{
            [MBProgressHUD showMessag:@"没有找到加密题" toView:self.view];
        }
    }];
}


-(void)ckdaQuestion:(DDTopicDataCellModel *)topicModel showAnswer:(BOOL)isShow
{
    _questions = topicModel.questions;
    NSMutableArray *qustionViews = [NSMutableArray array];
    for (int i = 0; i < _questions.count; i++)
    {
        DDTopicQuestion *question = _questions[i];
        TNColorViewData *viewData = [[TNColorViewData alloc] initWithCustomClass:[DDCkdaQuestion class]];
        viewData.question = question;
        viewData.page = i+1;
        viewData.total = _questions.count;
        viewData.topic = topicModel;
        viewData.typeIndex = _typeIndex;
        viewData.showAnswer = isShow;
        viewData.woAnswer = YES;
        [qustionViews addObject:viewData];
        
    }
    TNColorScrollViewConfig *config = [[TNColorScrollViewConfig alloc] initWithColorDataObjects:qustionViews bounces:YES showsHorizontalScrollIndicator:NO showsVerticalScrollIndicator:NO pagingEnabled:YES scrollHorizontal:YES];
    
    self.colorScrollVC = [[TNColorScrollViewController alloc] initWithColorScrollViewConfig:config displayMedia:NO cssStyle:DDCSSStyleReplay];
    self.colorScrollVC.topicID = _model.id;
    self.colorScrollVC.currentScrollerPage = ^(NSInteger currentPage){
        NSLog(@"%ld",(long)currentPage);
    };
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:self.colorScrollVC];
}


-(void)didselectSearchText:(NSNotification *)note
{
    NSLog(@"%@",note.object);
    NSString *string = note.object;
    if (string) {
        NSArray *arr = [string componentsSeparatedByString:@"_"];
        if (arr.count > 1) {
            
            NSMutableArray *tempDatas = [NSMutableArray array];
            int type = [arr[0] intValue];
            NSString *searchText = arr[1];
            if (_typeIndex == type) {
                
                if ([searchText isEqualToString:@"全部"]) {
                    _datas = _allArray;
                    [self.tableView reloadData];
                    return;
                }
                
                
                for (DDTopicDataCellModel *model in _allArray) {
                    NSArray *array = model.questions;
                    if (array.count > 0) {
                        //DDTopicQuestion *question = array[0];
                        //NSArray *array1 = question.body;
                        //if (array1.count > 0) {
                        //DDTopicQuestionBody *body = question.body[0];
                        //if (body.text&&[body.text rangeOfString:searchText].location != NSNotFound) {
                        if ([model.courseName isEqualToString:searchText]) {
                            [tempDatas addObject:model];
                           
                        }
                    }
                }
                _datas = tempDatas;
                [self.tableView reloadData];
            }
        }
    }
   
}


@end
